/*	browserNotice v1.0 beta
 *	http://browsernotice.com
 *
 *	Copyright 2010, Heath Dutton & Ben Shoults
 *	Released under the MIT License.	*/

com_browserNotice = function(){
	// Common but effective browser detection
	var browserCheck = {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "an unknown browser";
			this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1) {
						return data[i].identity;
					}
				} else if (dataProp) {
					return data[i].identity;
				}
			}
		},searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},dataBrowser: [{
				string: navigator.userAgent,
				subString: "Chrome",
				identity: "Chrome"
			},{
				string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Apple Safari",
				versionSearch: "Version"
			},{
				prop: window.opera,
				identity: "Opera"
			},{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},{ // for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},{ // for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
		}],dataOS : [{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},{
				string: navigator.userAgent,
				subString: "iPhone",
				identity: "iPhone/iPod Touch"
			},{
				string: navigator.userAgent,
				subString: "iPad",
				identity: "iPad"
			},{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}]
	};

	// Find the default language of the current browser
	function detectLanguage(){
		if (navigator.language != undefined) return navigator.language;
		if (navigator.browserLanguage != undefined) return navigator.browserLanguage;
		return false;
	}

	// a simple quick-fade function with easing-out. High browser compatibility is key here.
	var fading = false;
	this.fadeto = function(eid, opacity) {
		var element = document.getElementById(eid);	
		var newOpVal = parseFloat(element.style.opacity);
		if (newOpVal == null) {
			newOpVal = 0
		}	
		newOpVal = (newOpVal *.7) + (opacity *.3);	
		if (Math.round(newOpVal*100)/100 == opacity) {
			newOpVal = opacity;
		}		
		element.style.opacity = newOpVal;
		if (fading == false && opacity > 0) {
			element.style.display = 'block';
		}
		fading = true;
		element.style.filter = 'alpha(opacity = ' + (newOpVal * 100) + ')';		
		if (newOpVal == opacity) {
			if (opacity == 0) element.parentNode.removeChild(element);
			if (opacity == 1) element.style.filter = '';
			fading = false;
			return;
		}
		setTimeout("fadeto('" + eid + "'," + opacity + ")", 30);
	}
	
	// a simple method to set and recall a cookie
	function cookie(name, value, options) {
		if (typeof value != 'undefined') {
			// set cookie value
			options = options || {};
			if (value === null) {
				value = '';
				options.expires = -1;
			}
			var expires = '';
			if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
				var date;
				if (typeof options.expires == 'number') {
					date = new Date();
					date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000))
				} else {
					date = options.expires;
				}
				expires = '; expires=' + date.toUTCString()
			}
			var path = options.path ? '; path=' + (options.path) : '';
			var domain = options.domain ? '; domain=' + (options.domain) : '';
			var secure = options.secure ? '; secure' : '';
			document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('')
		} else {
			// get cookie value
			var cv = null;
			if (document.cookie && document.cookie != '') {
				var cs = document.cookie.split(';');
				for (var i = 0; i < cs.length; i++) {
					var co = cs[i].replace(/^\s+|\s+$/g,"");
					if (co.substring(0, name.length + 1) == (name + '=')) {
						cv = decodeURIComponent(co.substring(name.length + 1));
						break;
					}
				}
			}
			return cv;
		}
	}
	
	// dynamically adding css - works in IE6
	function addCss(cssCode) {
		var styleElement = document.createElement("style");
		styleElement.type = "text/css";
		if (styleElement.styleSheet) {
			styleElement.styleSheet.cssText = cssCode;
		} else {
			styleElement.appendChild(document.createTextNode(cssCode));
		}
		document.getElementsByTagName("head")[0].appendChild(styleElement);
	}
	
	// prevent destroying existing onload functions
	function addEvent(obj, evt, fn){
		if ( typeof obj.attachEvent != 'undefined'){
			obj.attachEvent( "on" + evt, fn );
		} else if ( typeof obj.addEventListener != 'undefined'){
			obj.addEventListener( evt, fn, false );
		} else {
			// May need to add support for ancient pre-historic browsers here.
		}
	}
	
	// see if the current browser is in a blacklist - requires a few bn vars to be set
	function browserIsBad(browsers){
		var hostb = bn.currentOS + ':' + bn.currentBrowser;
		var hostv = bn.currentVersion;
		for (var i in browsers) {
			if (i == hostb) {
				var tv = browsers[i];
				if (tv == '') return true;
				if (tv.indexOf('<') > -1){
					tv = tv.replace('<','');
					if (hostv < tv) {
						return true;
					} else {
						return false;	
					}
				} else if (tv.indexOf('>') > -1) {
					tv = tv.replace('>','');
					if (hostv > tv) {
						return true;
					} else {
						return false;	
					}
				} else if (hostv == tv) return true;
			}
		}
		return false;
	}
	
	// grab the document title
	function documentTitle() {
		var titleElement;
		if (document.getElementsByTagName) {
			titleElement = document.getElementsByTagName('title')[0];
			if (titleElement) return titleElement.nodeName;
		}
		return '';
	}
	
	// add our main event - core of the app
	addEvent(window, 'load', function(){
		// Detect the browser
		browserCheck.init();

		if (typeof browserNotice == "object") {
			var bn = browserNotice;
		} else {
			var bn = {};
		}

		// declare the default settings
		var def = {
			// enable testing mode to always show for all browsers, regardless of cookies. Good for debugging.
			testMode: false,
			// We use Google Analytics to track the effectiveness of this script, which we then use to optimize and improve upon it.
			// The analytics code is only loaded if the user's browser applies, and then only when they make a selection.
			// statsTracking is dissabled by default when in testMode.
			// You can opt-out of statistics tracking by setting statsTracking to false.
			statsTracking: true,
			// Set default colors for the overlay
			stylesBgColor: '000000',
			// Background opacity from 0 - 1
			stylesBgOpacity: .8,
			stylesInnerBgColor: 'FFFFFF',
			stylesTextColor: 'FFFFFF',
			// CSS styles to be applied to the document. The default here makes sure that the body spans the whole window in older browsers,
			// should this conflict with your css you can specify this variable to be null so that your CSS is not affected by this script.
			// Like everything else, this css is only applied to the current page when the end-user is applicable for the browser notice.
			stylesCSS: 'body{overflow:visible;width:100%;height:100%;margin:0;padding:0;}',
			// Delay the ability to ignore the notice by this many seconds. Forces the user to at least partially read the message. Must be 0 or larger.
			delay: 3,
			// By default the document title will be gathered from the title of the current page, but you can also customize this to be a static title.
			displayTitle: documentTitle(),
			// Use Google's translation API if available, and the content language is different than the browser language/
			// Note: Autotranslation requires that the Google Translation API is loaded prior to the execution of this script.
			translationEnabled: true,
			// Define source language so that we do not have to add Google's tranlation API overhead unless needed
			translationSource: 'en',
			translationRevert: 'Read this in English',
			// We specify browsers older than the 2002 generation and non-supported browser lines that can run Javascript
			// We do not use a whitelist, so that we do not accidentally display this notice to browsers of the future.
			browserCoreBlacklist: {
				'Windows:Explorer':'<7',
				'Mac:Explorer':'<6',
				'Windows:Netscape':'<10',
				'Mac:iCab':'<3',
				'Windows:Opera':'<7',
				'Mac:Opera':'<7'
				},
			// To add to the core blacklist without re-defining the whole list, just add to this secondary list
			browserAddToBlacklist: {},
			// Name of browser reccomended, as predefined
			browserReccomended: 'Google Chrome',
			// Absolute link to an image logo for the browser
			browserLogo: 'http://www.google.com/tools/dlpage/res/chrome/images/chrome-205_noshadow.png',
			// Link to reccomended browser's download page (should be a universal OS/language landing page)
			browserDownloadLink: 'http://www.google.com/chrome/eula.html',
			// The following should be set automatically, unless you are doing some sort of testing
			currentBrowser: browserCheck.browser,
			currentVersion: browserCheck.version,
			currentOS: browserCheck.OS,
			// Define the default html that will be displayed in the center of the screen. This should be as textual as possible,
			// refrain from graphical text which cannot be auto-translated.
			// Try to keep the message simple, to the point, polite and as convincing as possible without insulting the user.
			// If you modify any styles, be sure to browser test as far back into the dark ages as possible.
			// Dynamic variables you can use here:
			// {browserCurrent} - will output the current browser that was detected
			// You can also use any other string-based variables as tags. ie: {browserReccomended} (these are case sensitive for the sake of efficiency)
			content: '<div>Looks like you are using {currentBrowser} {currentVersion} for {currentOS}</div><br><a href="http://lwtconnect.com" target="_blank"><img src="http://lwtconnect.com/underdev/underdev.png" width="300" height="38" style="border: 0;"></a><br><br><br><div style="width:500px; margin: 0 auto;"><div style="position:relative; left:5px; text-align:left;font-size:11px; padding-left:40px; line-height:18px;font-weight:normal;">Please note:<br>&nbsp;&nbsp;&nbsp;&nbsp;&bull;&nbsp;&nbsp;What you see here should not be considered complete or final in any way, shape, or form.<br>&nbsp;&nbsp;&nbsp;&nbsp;&bull;&nbsp;&nbsp;The content, design, and code are in flux which can cause unusual<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;or undesired effects while the site is in this development stage.<br>&nbsp;&nbsp;&nbsp;&nbsp;&bull;&nbsp;&nbsp;You will not be bothered by this notice again while browsing the pre-developed site.<br>&nbsp;&nbsp;&nbsp;&nbsp;&bull;&nbsp;&nbsp;This notice will also be removed when the site becomes officially live.</div><br><br><br>'+
			'<div id="ignoreNotice" style="display:none;position:absolute;left:50%;opacity:0;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity:0;"><a href="javascript:com_browserNotice_ignore();">Ignore this notice</a></div><div id="languageRevert" style="display:none;" class="notranslate"><a href="javascript:browserNoticeRevert();">{translationRevert}</a></div>'
		};
		
		// step through the object and assign defaults where they have not been preset externally
		for (var n in def) {
			if (!bn.hasOwnProperty(n)) bn[n] = def[n];
		}
		
		// Check if the browser is on the blacklist.
		if (bn.testMode || browserIsBad(bn.browserCoreBlacklist)) {
			// check if this user has already been excluded by cookie
			if (bn.testMode || cookie("browserNotice") != "1") {
				// Apply styles if defined
				if (bn.stylesCSS != null && bn.stylesCSS != undefined && bn.stylesCSS.length > 0) addCss(bn.stylesCSS);

				// Load Google Analytics so that we can check the user's choice momentarily 
				if (!bn.testMode && bn.statsTracking) {
					if(typeof _gat == 'undefined') {
						// Since the page hasn't loaded ga.js yet, use asynchronous mode to load it
						var _gaq = _gaq || [];
						_gaq.push(['_setAccount', 'UA-16347485-1']);
						_gaq.push(['_trackPageview']);						
						(function() {
							var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
							ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
							var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
						})();
					} else {
						// ga.js has already loaded, we just need to make the call...
						try {
							var pageTracker = _gat._getTracker("UA-16347485-1");
							pageTracker._setDomainName("none");
							pageTracker._setAllowLinker(true);
							pageTracker._trackPageview();
						} catch(err) {}
					}
				}
				
				// Do a search & replace on the content for other custom variables
				for (var n in bn) {
					if (n != 'content') bn.content = bn.content.replace(RegExp('{'+n+'}', 'g'), bn[n]);
				}

				// Add the overlay content to the body
				var bo = document.getElementsByTagName('body')[0];
				if (bo == null) bo = document.createElement('body');
				var overlay = document.createElement('div');
				overlay.innerHTML = '<div id="browserNoticeOverlay" style="margin:0;padding:0;border:0;outline:0;position:fixed !important;position:absolute;top:0px;left:0px;height:100%;width:100%;z-index:2147483646;overflow:visible;opacity:0;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity:0;background:#' + bn.stylesBgColor + ';"></div><div id="browserNoticeContentHolder" style="margin:0;padding:0;border:0;outline:0;position:fixed !important;position:absolute;top:0px;left:0px;height:100%;width:100%;z-index:2147483647;overflow:visible;opacity:0;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity:0;background:transparent;color:#' + bn.stylesTextColor + '"><table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0"><tr><td valign="middle" align="center"><div id="browserNoticeContent">' + bn.content + '</div></td></tr></table></div>';
				bo.appendChild(overlay,bo.firstChild);
				
				// Check if we need to (and can) translate the content
				if (google.language){
					var browserLang = detectLanguage();
					if (bn.translationEnabled && browserLang.indexOf(bn.translationSource) == -1) {
						// Setup function for returning to original language
						browserNoticeOC = bn.content; // set original content for retrieval later
						browserNoticeRevert = function(){
							browserNoticeRevert = function(){};
							document.getElementById("browserNoticeContent").innerHTML = browserNoticeOC;
							addCss('#languageRevert{display:none !important;}');
						}
						// translate content
						google.language.translate(bn.content, bn.translationSource, browserLang, function(result) {
							if (!result.error){
								//var container = document.getElementById("browserNoticeContent");
								document.getElementById("browserNoticeContent").innerHTML = result.translation;
								// Add return to previous language button
								addCss('#languageRevert{display:block !important;}');
							}
						});
					}
				}
				
				// Begin fadein
				fadeto('browserNoticeOverlay', bn.stylesBgOpacity);
				fadeto('browserNoticeContentHolder', 1);
				
				// Show ignore link/button
				com_browserNotice_show = function(){
					// Function for ignoring the notice
					com_browserNotice_ignore = function(){
						if (!fading) {
							com_browserNotice_ignore = function(){};
							fadeto('browserNoticeOverlay', 0);
							fadeto('browserNoticeContentHolder', 0);
							cookie("browserNotice", "1");
							if (!bn.testMode && bn.statsTracking) {
								if(typeof _gat != 'undefined') {
									pageTracker._trackPageview("/bn_ignore");
								}
							}
						}
					}
					fadeto('ignoreNotice', 1);
				}
				setTimeout(com_browserNotice_show, 1000 * bn.delay);
				
				// Set up download linkability
				com_browserNotice_accept = function(){
					if (!bn.testMode && bn.statsTracking) {
						if(typeof _gat != 'undefined') {
							pageTracker._trackPageview("/bn_accept");
						}
					}
					return;
				}
			} else {
				cookie("browserNotice", "1");
			}
		}
	});
}
com_browserNotice();